from datetime import datetime
from pathlib import PurePath, Path
import stat
import os
import shutil

from .data import extension_to_icon


def get_relative_path(short_part, long_path):
    return PurePath(long_path).relative_to(PurePath(short_part))


def get_file_icon_class(filename):
    ext = os.path.splitext(filename.lower())[1]
    if ext.startswith('.'):
        ext = ext[1:]
    return extension_to_icon(ext)


def convert_size_to_str(size):
    units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
    unit_idx = 0
    while size > 1024:
        if unit_idx+1 >= len(units):
            break
        unit_idx += 1
        size /= 1024
    return f'{size:{.2}f} {units[unit_idx]}'


def convert_mode_to_str(mode):
    return str(oct(stat.S_IMODE(mode)))[2:]


def convert_time_to_str(timestamp):
    return datetime.fromtimestamp(timestamp).strftime("%Y/%-m/%d %H:%M:%S")


def get_folder_size(folder):
    total_size = 0
    for dirpath, dirnames, filenames in os.walk(folder):
        for f in filenames:
            fp = os.path.join(dirpath, f)
            # skip if it is symbolic link
            if not os.path.islink(fp):
                total_size += os.path.getsize(fp)
    return total_size


def remove_starting_slash(s):
    i = 0
    if s.startswith('/'):
        while i < len(s) and s[i] == '/':
            i += 1
    return s[i:]

def copy_folder(from_folder, to_parent_folder, to_name):
    to_folder = os.path.join(to_parent_folder, to_name)
    os.makedirs(to_folder, exist_ok=True)
    for item in os.listdir(from_folder):
        s = os.path.join(from_folder, item)
        d = os.path.join(to_folder, item)
        if os.path.isdir(s):
            shutil.copytree(s, d)
        else:
            shutil.copy2(s, d)


def do_copy(from_path, to_folder, newname):
    if from_path.is_file():
        to_filepath = os.path.join(to_folder, newname)
        shutil.copy(from_path, to_filepath)
    else:
        copy_folder(from_path, to_folder, newname)


def do_move(from_path, to_folder, newname):
    to_path = os.path.join(to_folder, newname)
    shutil.move(from_path, to_path)
    